# 读取文件
with open('report.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
# print(lines)

# 格式化文件
data = [line.strip().split(' ') for line in lines]  # print(len(data))  31  # print(len(data[0]))  10

# 新建总和列表，用于计算新增项—整体平均分
new_sum_list = []

# 字符串转数字，计算新增总分与平均值，‘不及格’替换
for i in range(1, 31):
    int_numbers = [int(num) for num in data[i][1:10]]
    zong_fen = int(sum(int_numbers))
    ping_jun_fen = round((zong_fen / 9), 1)
    data[i].append(str(zong_fen))
    data[i].append(str(ping_jun_fen))
    convert_list = [int(item) for item in data[i] if item.isdigit()]
    new_sum_list.append(convert_list)
    convert_list = [item if item >= 60 else '不及格' for item in convert_list]
    data[i][1:11] = convert_list

# 完成新增的第二行内容，即各科总分平均分
sublist_length = len(new_sum_list[0])
result = [0] * sublist_length
for i in new_sum_list:
    for j in range(sublist_length):
        result[j] = result[j] + i[j]
result_average = [round(x / 30, 0) for x in result]
zong_ping_jun = round(result[-1] / 270, 1)
result_average.append(zong_ping_jun)
result_average.insert(0, '平均')
result_average.insert(0, '--')

# 完善首行名称
data[0].insert(0, '名次')
data[0].append('总分')
data[0].append('平均分')

# 排序
part_data = data[1:31]
part_data_sorted = sorted(part_data, key=lambda item: item[-2], reverse=True)  # print(len(part_data_sorted))  30
pai_ming_list = [i for i in range(1, 31)]
for i in range(30):
    part_data_sorted[i].insert(0, pai_ming_list[i])
data[1:31] = part_data_sorted

# 插入新增的第二行，形成统计分析表,新分析表格式化为字符串
data.insert(1, result_average)
new_data = []
for i in data:
    str_data = [str(item) for item in i]
    new_data.append(str_data)
new_result = ''
for i in new_data:
    he_bing = '  '.join(i)
    new_result = new_result + he_bing + '\n'

    # 导出并创建新文件
with open('result.txt', 'w', encoding='utf-8') as f:
    f.writelines(new_result)
